<template>
	<view class="containers">
		<nav-bar :title="$t('客服')" leftIcon="left"></nav-bar>
		<!-- <span style="color: #fff;">{{scrollHeight}}</span> -->
		<scroll-view class="scroll-y" scroll-y="true" style="" :scroll-top="scrollHeight" :scroll-into-view="bottomId">
			<!-- v-for="(item,i) in list" :key="i" -->
			<view v-for="(item, index) in listContent" :key="index">
				<view class="listMain" v-if="item.messageType == 2">
					<view class="left">
						<image src="@/static/user.png" class="img"></image>
						<view class="leftList">
							<view class="time">
								{{ item.createTimeStr }}
							</view>
							<view class="text">
								{{ item.messageText }}
							</view>
						</view>
					</view>
				</view>
				<view class="listMains" v-if="item.messageType == 1">
					<view class="right">
						<view class="leftList">
							<view class="time">
								{{ item.createTimeStr }}
							</view>
							<view class="text">
								{{ item.messageText }}
							</view>
						</view>
						<image src="@/static/user.png" class="img"></image>
					</view>
					<view class="imgList" v-if="item.picOne != null">
						<image :src="item.picOne" class="imsa" v-if="item.picOne" @click="previewImg(item.picOne)">
						</image>
						<image :src="item.picTwo" class="imsa" v-if="item.picTwo" @click="previewImg(item.picTwo)">
						</image>
						<image :src="item.picThree" class="imsa" v-if="item.picThree" @click="previewImg(item.picThree)">
						</image>
						<image :src="item.picFour" class="imsa" v-if="item.picFour" @click="previewImg(item.picFour)">
						</image>
						<image :src="item.picFive" class="imsa" v-if="item.picFive" @click="previewImg(item.picFive)">
						</image>
						<image :src="item.picSix" class="imsa" v-if="item.picSix" @click="previewImg(item.picSix)">
						</image>
					</view>
				</view>
			</view>
			<view :id="'p' + (listContent.length)"></view>
			<!-- <div class="product" id="productId"></div> -->
		</scroll-view>
		<view class="bottom">
			<view class="bottomMain">
				<view class="ipt">
					<input @keydown.enter="submit" v-model="text" class="textarea" :placeholder="$t('請輸入您的内容')"
						style="padding: 20rpx" />
					<view @click="submit" class="btn"
						style="background: linear-gradient(90deg, #039bda, #0ff3f7);border-radius: 10rpx;margin-left: 10rpx; ">
						{{ $t("發送") }}
					</view>
				</view>
				<uni-section type="line">
					<view class="example-body">
						<!--album:从相册中选择,compressed压缩图  -->
						<uni-file-picker :sizeType="['compressed']" v-model="imgfileList" file-mediatype="image"
							@delete="del" @select="select" limit="6" :title="$t('最多選擇6張圖片')"
							style="color: #999"></uni-file-picker>
					</view>
				</uni-section>
			</view>

		</view>
	</view>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import msgListData from '@/hooks/msgList.js'
import { axios, socketUrl, axiosLogin } from '@/service/request.js'
import i18n from '@/locale/index'
import { getCurrentFormattedTime } from "../../utils/check";
import {
	onShow,
	onReachBottom,
	onReady,
	onUnload,
	onHide
} from '@dcloudio/uni-app'
const {
	getXxList
} = msgListData()
const scrollHeight = ref(0)
//v-model绑定的图片列表 ,用来清空用
const imgfileList = ref([])
const bottomId = ref('')
//文件列表
const fileList = ref([]);
const appfileList = ref([]);

//图片base64列表
const imgList = ref([]);

//文字内容
const text = ref("");
//聊天列表
const listContent = ref([])

const heightbom = ref(999999999)

const errNum = ref(0)



//上传图片
async function select(e) {
	//#ifdef APP-PLUS
	e.tempFilePaths = await Promise.all(
		e.tempFilePaths.map(async (item, index) => {
			const res = await new Promise((resolve, reject) => {
				uni.compressImage({
					src: item,
					quality: 10,
					success: res => {
						// e.tempFilePaths[index] = res.tempFilePath
						resolve(res.tempFilePath);
					},
					fail: reject
				});
			});
			return res
		})
	);
	//#endif
	appfileList.value = [...appfileList.value, ...e.tempFilePaths];
	fileList.value = [...fileList.value, ...e.tempFiles];
}

//删除图片
function del(e) {
	fileList.value = fileList.value.filter((item) => {

		return item.name !== e.tempFile.name;
	});
}

//发送聊天内容
async function submit() {
	if (!text.value) {
		return uni.showToast({
			title: `${i18n.global.t('留言內容不能為空')}!`,
			icon: 'none',
		})
	}
	if (!isOpenSocket.value) {
		return
		//  uni.showToast({
		// 	title: `WebSocket ERROR !`,
		// 	icon: 'error',
		// })
	}
	// uni.showLoading({
	// 	title: `${i18n.global.t('發送中')}...`
	// });


	//#ifdef APP-PLUS
	const compress = appfileList.value.map((item) => {
		return new Promise((resolve) => {
			apptobase(item, (base64) => {
				resolve(base64);
			});
		});
	});

	const compresse = await Promise.all(compress);
	imgList.value.push(...compresse);

	// #endif

	//#ifdef H5
	const compressPromises = fileList.value.map(async (item) => {
		const res = await compressPic(item.file, 0.1);
		return res;
	});
	//等待执行完毕再去调接口
	const compressedImages = await Promise.all(compressPromises);
	imgList.value.push(...compressedImages);
	//#endif

	//websocket发送消息
	SocketTask.value.send({
		data: JSON.stringify({
			userId: uni.getStorageSync("setUserInfo").userId,
			msg: text.value,
			consumerId: uni.getStorageSync("setUserInfo").customerId,
			type: 1, //1:用户 2:客服    当前用户的类型,
			picList: imgList.value
		}),
		async success(data) {
			listContent.value.push({
				userId: uni.getStorageSync("setUserInfo").userId,
				messageText: text.value,
				picOne: imgList.value[0],
				picTwo: imgList.value[1],
				picThree: imgList.value[2],
				picFour: imgList.value[3],
				picFive: imgList.value[4],
				picSix: imgList.value[5],
				messageType: 1,
				createTimeStr: getCurrentFormattedTime(),
			})
			nextTick(() => {
				// const height = document.querySelector('.uni-scroll-view-content')
				heightbom.value = heightbom.value + 100000
				scrollHeight.value = heightbom.value
			})
		},
	});

	// 留言调接口
	axiosLogin('messageBoard/addMessageBoard', {
		userId: uni.getStorageSync("setUserInfo").userId,
		messageText: text.value,
		picList: imgList.value,
		messageType: 1,
	})

	text.value = ''
	imgList.value = []
	fileList.value = []
	imgfileList.value = []
	fileList.value = []
	appfileList.value = []
	// uni.hideLoading();

}


function apptobase(path, callback) {
	plus.io.resolveLocalFileSystemURL(path, function (entry) {
		entry.file(function (file) {
			var fileReader = new plus.io.FileReader();
			fileReader.readAsDataURL(file);
			fileReader.onloadend = function (evt) {
				let base64 = 'data:image/octet-stream;base64,' + evt.target.result.split(",")[1];
				callback(base64); // 将结果通过回调函数返回
			};
		});
	});
}

//图片压缩及转base64
function compressPic(file, quality) {
	return new Promise((resolve, reject) => {
		let reads = new FileReader();
		reads.readAsDataURL(file); //
		reads.onload = ({ target: { result: src } }) => {
			var canvas = document.createElement("canvas");
			var ctx = canvas.getContext("2d");
			var img = new Image();
			img.src = src;
			img.onload = function () {
				let width = img.width;
				canvas.width = width;
				canvas.height = width * (img.height / img.width);
				ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
				let data = canvas.toDataURL("image/jpeg", quality).replace("image/jpeg",
					"image/octet-stream");
				resolve(data); // 使用 resolve 返回处理后的结果
			};
		};
		reads.onerror = (error) => {
			reject(error); // 使用 reject 处理可能的错误
		};
	});
}

//获取聊天列表
const getList = async (e) => {
	let list = {
		userId: uni.getStorageSync('setUserInfo').userId
	}
	let num = 0
	const data = await getXxList('messageBoard/queryMessageBoard', list)
	listContent.value = data
	// listContent.value.map(x => {

	// 	if (x.messageType == 1 || x.picOne == null) {
	// 		num = num += 62.5
	// 	} else if (x.messageType == 2 || x.picOne != null) {
	// 		num = num += 112.5
	// 	}
	// 	scrollHeight.value = num
	// })
	nextTick(() => {
		// const height = document.querySelector('.uni-scroll-view-content')
		heightbom.value = heightbom.value + 100000
		scrollHeight.value = heightbom.value
	})
	// setTimeout(() => {
	// 	let num = listContent.value.length
	// 	bottomId.value = 'p' + (num)
	// }, 500)
}

onReady(() => { })
//每次进入页面都会执行，声明time
// let time
// getList()
onShow(() => {
	getList()
	initSocket()
	if (time) {
		clearInterval(time)
	}
})

onMounted(() => {
	// initSocket()
})

//预览图片
function previewImg(photoImg) {
	let imgsArray = [];
	imgsArray[0] = photoImg;
	uni.previewImage({
		current: 0,
		urls: imgsArray
	});
}

//离开页面时触发
onUnload(() => {
	if (time) {
		clearInterval(time)
	}
	closeSocket()
})




const SocketTask = ref(null) //socket实例
const isOpenSocket = ref(false) //判断socket是否连接成功

let time = null
//初始化socket
function initSocket() {
	SocketTask.value = uni.connectSocket({
		url: socketUrl + `${uni.getStorageSync("setUserInfo").userId}` +
			`/1/${uni.getStorageSync("setUserInfo").customerId}`,
		// header: {
		// 	'content-type': 'application/json'
		// },
		// protocols: ['protocol1'],
		// method: 'POST',
		success(data) {
		},
	});
	// 监听WebSocket连接打开事件
	SocketTask.value.onOpen((data) => {
		isOpenSocket.value = true

		// 注：只有连接正常打开中 ，才能正常收到消息
		if (isOpenSocket.value) {
			SocketTask.value.onMessage((res) => {
				console.log('收到服务器内容!!!!!!!!!：');
				console.log(res);
				errNum.value = 0
				if (res.data === '连接成功') {
					return
				}
				const data = JSON.parse(res.data)
				switch (data.contentType) {
					// case 1:
					// 	listContent.value = data.boardList
					// 	break;
					case 2:
						listContent.value.push({
							userId: uni.getStorageSync("setUserInfo").userId,
							messageText: data.messageText,
							messageType: 2,
							createTimeStr: getCurrentFormattedTime(),
						})
						break;
				}
				nextTick(() => {
					// const height = document.querySelector('.uni-scroll-view-content')
					heightbom.value = heightbom.value + 1000000
					scrollHeight.value = heightbom.value
				})
			});
		} else {
			uni.showToast({
				title: `${i18n.global.t('連接已斷開,請刷新頁面')}!`,
				icon: 'error',
			})
		}
	})
	//监听 WebSocket 错误事件
	SocketTask.value.onError((errMsg) => {
		console.log(errMsg);
		console.log('WebSocket连接打开失败，请检查！!!!!!!!!!!!!!!');
		if (time) {
			clearInterval(time)
		}
		if (errNum.value >= 4) {
			console.log('刷新了！！！！！！！！！', 'pages\Customer\Customer.vue-第424行')
			return uni.redirectTo({
				url: '/pages/Customer/Customer'
			});
		}
		time = setTimeout(() => {
			initSocket()
			errNum.value++
			getList()
		}, 1000)
	})

	// 这里仅是事件监听【如果socket关闭了会执行】
	SocketTask.value.onClose((code) => {
		isOpenSocket.value = false;
		if (code.code == 1000) {
			return
		}
		if (time) {
			clearInterval(time)
		}

		if (errNum.value >= 4) {
			return uni.redirectTo({
				url: '/pages/Customer/Customer'
			});

			// uni.showToast({
			// 	title: `${i18n.global.t('連接已斷開,請刷新頁面')}!`,
			// 	icon: 'error',
			// })
		}
		time = setTimeout(() => {
			initSocket()
			errNum.value++
			getList()
		}, 1000)
	});

}

// 关闭websocket【离开这个页面的时候执行关闭】
function closeSocket() {
	SocketTask.value.close({
		success(res) {
			isOpenSocket.value = false;
		},
		fail(err) {
		},
	});
}

onHide(() => {
	if (time) {
		clearInterval(time)
	}
	closeSocket()
})
</script>

<style lang="scss" scoped>
.scroll-y {

	/*#ifdef APP-PLUS */
	height: calc(100vh - 310rpx - 5rem);
	/* #endif */
	/* #ifdef H5 */
	height: calc(53vh);
	/* #endif */
	background-color: #24232c;
}

:deep(.uni-file-picker) {
	margin-top: 40rpx !important;
}

:deep(.file-picker__box) {
	width: 100rpx !important;
	height: 100rpx !important;
	padding-top: 0;

	.file-picker__progress {
		display: none;
	}
}

:deep(.file-picker__box-content) {
	border-style: dashed !important;
	border-radius: 16rpx !important;

	.icon-add {
		width: 60rpx;
		height: 4rpx;
	}

	.icon-del-box {
		height: 32rpx;
		width: 32rpx;
		top: 0;
		right: 0;
		z-index: 99;
		background-color: #F72E2E;
		opacity: 0.6;

		.icon-del {
			width: 16rpx;
			height: 2rpx;
		}
	}
}

.bottom {
	position: fixed;
	bottom: 0;
	height: 310rpx;
	// background-color: #0df2ed;
}

.line {
	width: 100%;
	height: 25rpx;
}



.example-body {
	padding: 10px;
	padding-top: 0;
}

.custom-image-box {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
}

.text {
	font-size: 14rpx;
	color: #999;
}

.bottomMain {
	padding: 25rpx;
}

.ipt {
	display: flex;
	justify-content: center;
	align-items: center;

	.textarea {
		color: #fff;
		border: 1rpx solid #4b4b4b;
		width: 500rpx;
		margin-top: 1rpx;
	}

	.btn {
		width: 150rpx;
		height: 80rpx;
		background: linear-gradient(90deg, #5641dd, #b1a6fd);
		text-align: center;
		line-height: 80rpx;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #ffffff;
	}
}

.list {
	height: 75vh;
	background-color: #0df2ed;
}

.imgList image {
	width: 100rpx;
	height: 100rpx;
	border-radius: 25rpx;
	margin-left: 15rpx;
}

.imgList {
	// justify-content: right;
	display: block;
	flex-direction: row-reverse;
	display: flex;
	margin-right: 80rpx;
	margin-top: 10rpx;
}

.right {
	display: flex;
	align-items: flex-start;
	justify-content: right;
	text-align: right;

}

.leftList {
	margin-left: 15rpx;
}

.left {
	display: flex;
	align-items: flex-start;
}

.img {
	display: block;
	width: 75rpx;
	height: 75rpx;
	border-radius: 50%;
}

.imgs {
	width: 75rpx;
	height: 75rpx;
	border-radius: 50%;
	text-align: right;
	margin-left: 15rpx;
}

.moneyNameKk2 {
	width: 180rpx;
	height: 60rpx;
	background: #b3b3b3;
	border-radius: 10rpx;
	text-align: center;
	line-height: 60rpx;
	margin-right: 25rpx;
}

.moneyNameKk {
	width: 180rpx;
	height: 60rpx;
	background: linear-gradient(90deg, #039bda, #0df2ed);
	border-radius: 10rpx;
	text-align: center;
	line-height: 60rpx;
	margin-right: 25rpx;
}

.typeList {
	display: flex;
	align-items: center;
	padding: 35rpx;
	position: fixed;
	top: 150rpx;
	background-color: rgb(24, 23, 30);
	width: 100%;
}

.listMainLine {
	padding: 25rpx 45rpx;
	background: #24232c;
	// border-radius: 20rpx;
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	border: 1rpx solid #4b4b4b;
	margin-bottom: 15rpx;
}

.text {
	color: #ffffff;
	font-size: 28rpx;
	word-break: break-all;
	white-space: normal;
	width: 600rpx;
}

.time {
	color: #808492;
	font-size: 24rpx;
}

.listMain {
	padding: 25rpx 25rpx;
	// background: #24232c;
	// border-radius: 20rpx;
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	// border-bottom: 1rpx solid #4b4b4b;
	// margin-bottom: 15rpx;
}

.listMains {
	padding: 25rpx 25rpx;
	// background: #24232c;
	// border-radius: 20rpx;
	// display: flex;
	// align-items: flex-start;
	// justify-content: space-between;
	// border-bottom: 1rpx solid #4b4b4b;
	// margin-bottom: 15rpx;
}
</style>